import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';
import type { PluginOption } from 'vite';
import { defineConfig, loadEnv } from 'vite';
import { checker } from 'vite-plugin-checker';
import viteCompression from 'vite-plugin-compression';
import svgr from 'vite-plugin-svgr';
import tsconfigPaths from 'vite-tsconfig-paths';

export default ({ mode }: { mode: string }) => {
  const VITE_BASE_URL = loadEnv(mode, process.cwd()).VITE_BASE_URL;

  const plugins = [
    react(),
    checker({
      typescript: true,
      eslint: { lintCommand: 'eslint "./src/**/*.{js,jsx,ts,tsx}"' },
      overlay: false,
    }),
    tsconfigPaths(),
    visualizer({ template: 'sunburst' }) as unknown as PluginOption,
    svgr(),
    viteCompression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz',
    }),
  ];

  return defineConfig({
    plugins,
    build: {
      rollupOptions: {
        output: {
          manualChunks: {
            react: ['react', 'react-dom'],
            chakra: ['@chakra-ui/react'],
            emotion: ['@emotion/react', '@emotion/styled'],
            framerMotion: ['framer-motion'],
            icons: ['@chakra-ui/icons'],
            router: ['react-router-dom'],
            other: ['axios'],
          },
        },
      },
    },
    server: {
      // open: true,
      proxy: {
        '/api/': {
          target: VITE_BASE_URL,
          changeOrigin: true,
        },
      },
    },
  });
};
